import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'permission_state.dart';
import '../../routes/app_pages.dart';
import '../../data/services/preferences_service.dart';

/// 权限授权逻辑控制器 - Permission Authorization Logic Controller
///
/// 管理Android平台的权限请求和授权流程
/// Manages permission requests and authorization flow for Android platform
class PermissionLogic extends GetxController {
  final PermissionState state = PermissionState();
  
  // 权限授权状态存储键 - Permission authorization status storage key
  static const String _permissionGrantedKey = 'permission_granted';
  static const String _permissionCheckedKey = 'permission_checked';

  @override
  void onInit() {
    super.onInit();
    _checkPermissionStatus();
  }

  /// 检查权限状态 - Check Permission Status
  /// 检查是否已经授权过，如果已授权则直接跳转到闪屏页面
  /// Check if already authorized, if so, navigate directly to splash screen
  Future<void> _checkPermissionStatus() async {
    try {
      final preferencesService = Get.find<PreferencesService>();
      
      // 检查是否已经处理过权限 - Check if permissions have been handled
      final isChecked = await preferencesService.getBool(_permissionCheckedKey) ?? false;
      final isGranted = await preferencesService.getBool(_permissionGrantedKey) ?? false;
      
      if (isChecked && isGranted) {
        // 已经授权过，直接跳转到闪屏页面 - Already authorized, navigate directly to splash screen
        Get.offAllNamed(Routes.splash);
        return;
      }
      
      // 如果是非Android平台，直接跳转 - If not Android platform, navigate directly
      if (!Platform.isAndroid) {
        await _savePermissionStatus(true, true);
        Get.offAllNamed(Routes.splash);
        return;
      }
      
      // Android平台且未处理过权限，显示权限页面 - Android platform and permissions not handled, show permission page
      // 权限页面会自动显示，无需额外操作
    } catch (e) {
      // 如果获取状态失败，继续显示权限页面 - If getting status fails, continue showing permission page
      print('检查权限状态失败 - Failed to check permission status: $e');
    }
  }

  /// 用户点击不同意 - User clicks disagree
  void onDisagree() async {
    try {
      // 保存用户拒绝状态 - Save user rejection status
      await _savePermissionStatus(false, true);
      
      // 退出应用 - Exit app
      if (Platform.isAndroid) {
        SystemNavigator.pop();
      }
    } catch (e) {
      print('保存拒绝状态失败 - Failed to save rejection status: $e');
      SystemNavigator.pop();
    }
  }

  /// 用户点击同意 - User clicks agree
  void onAgree() async {
    try {
      state.isLoading = true;
      update();

      // 请求必要权限 - Request necessary permissions
      bool permissionsGranted = await _requestPermissions();

      if (permissionsGranted) {
        // 保存授权状态 - Save authorization status
        await _savePermissionStatus(true, true);

        // 导航到闪屏页面 - Navigate to splash screen
        Get.offAllNamed(Routes.splash);
      } else {
        // 权限被拒绝，保存状态但不跳转 - Permissions denied, save status but don't navigate
        await _savePermissionStatus(false, true);
        
        Get.snackbar(
          '权限请求失败',
          '部分权限被拒绝，应用功能可能受限',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.orange,
          colorText: Colors.white,
        );
      }
    } catch (e) {
      // 权限请求失败，显示错误信息 - Permission request failed, show error
      Get.snackbar(
        '权限请求失败',
        '无法获取必要权限，请在设置中手动开启',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    } finally {
      state.isLoading = false;
      update();
    }
  }

  /// 保存权限状态 - Save Permission Status
  /// 将权限授权状态保存到本地存储
  /// Save permission authorization status to local storage
  Future<void> _savePermissionStatus(bool granted, bool checked) async {
    try {
      final preferencesService = Get.find<PreferencesService>();
      await preferencesService.setBool(_permissionGrantedKey, granted);
      await preferencesService.setBool(_permissionCheckedKey, checked);
    } catch (e) {
      print('保存权限状态失败 - Failed to save permission status: $e');
    }
  }

  /// 请求必要权限 - Request necessary permissions
  /// 返回是否成功获取关键权限 - Returns whether critical permissions were successfully obtained
  Future<bool> _requestPermissions() async {
    if (!Platform.isAndroid) return true;

    try {
      // 定义需要的权限列表 - Define required permissions list
      List<Permission> permissions = [
        Permission.storage,
        Permission.manageExternalStorage,
        Permission.notification,
      ];

      // 检查Android版本，Android 13+需要不同的权限 - Check Android version, Android 13+ needs different permissions
      if (Platform.isAndroid) {
        permissions.addAll([
          Permission.photos,
          Permission.videos,
          Permission.audio,
        ]);
      }

      // 请求权限 - Request permissions
      Map<Permission, PermissionStatus> statuses = await permissions.request();

      // 检查关键权限是否被授予 - Check if critical permissions are granted
      bool hasStoragePermission =
          statuses[Permission.storage]?.isGranted == true ||
              statuses[Permission.manageExternalStorage]?.isGranted == true ||
              statuses[Permission.photos]?.isGranted == true;

      if (!hasStoragePermission) {
        // 如果关键权限被拒绝，显示提示但不阻止应用继续 - If critical permissions are denied, show prompt but don't block app
        _showPermissionDialog();
        return false;
      }

      return true;
    } catch (e) {
      print('请求权限时出错 - Error requesting permissions: $e');
      return false;
    }
  }

  /// 显示权限提示对话框 - Show Permission Prompt Dialog
  void _showPermissionDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('权限提示'),
        content: const Text('存储权限是应用正常运行的必要权限，请在设置中手动开启。'),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
              openAppSettings();
            },
            child: const Text('去设置'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              // 继续使用应用，但功能可能受限 - Continue using app but with limited functionality
              Get.offAllNamed(Routes.splash);
            },
            child: const Text('继续使用'),
          ),
        ],
      ),
      barrierDismissible: false,
    );
  }

  /// 重置权限状态 - Reset Permission Status
  /// 用于测试或重新授权 - For testing or re-authorization
  Future<void> resetPermissionStatus() async {
    try {
      final preferencesService = Get.find<PreferencesService>();
      await preferencesService.setBool(_permissionGrantedKey, false);
      await preferencesService.setBool(_permissionCheckedKey, false);
    } catch (e) {
      print('重置权限状态失败 - Failed to reset permission status: $e');
    }
  }
}
